package com.acoreful.acf2admin.commons.utils;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Collection;

import org.apache.commons.io.FilenameUtils;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;

public class FileUtils extends org.apache.commons.io.FileUtils {
	
	private static String FILENAME_RULE="{0}_({1}).{2}";
	/**
	 * @param srcDir
	 * @param destFile
	 * @throws IOException
	 */
	public static void copyFileToDirectoryAndNoOverlay(File srcFile,
			File destDir) throws IOException {
		if (destDir == null) {
			throw new NullPointerException("Destination must not be null");
		}
		if (destDir.exists() && destDir.isDirectory() == false) {
			throw new IllegalArgumentException("Destination '" + destDir
					+ "' is not a directory");
		}
		File destFile = new File(destDir, srcFile.getName());
		//System.out.println("源文件：" + destFile.getAbsolutePath());
		destFile = autoRename(destFile);
		//System.out.println(destFile.getAbsolutePath());
		copyFile(srcFile, destFile, true);
	}

	/**
	 * 自动重命名
	 * @param file
	 * @return
	 */
	private static File autoRename(File file) {
		String tempFilename = FilenameUtils.removeExtension(file
				.getAbsolutePath());
		String fileExtension = FilenameUtils.getExtension(file.getName());
		File tempFile = file;
		int i = 1;
		while (true) {
			if (tempFile.exists()) {
				tempFile = getFile(MessageFormat.format(FILENAME_RULE,
						tempFilename, String.valueOf(i++), fileExtension));
				continue;
			}
			break;
		}
		return tempFile;
	}

	public static void main(String[] args) {
		System.out.println(FilenameUtils
				.removeExtension("D:\\temp\\测试.xlsx"));
		File srcFile = getFile("D:\\temp\\测试.xlsx");
		System.out.println(srcFile.getName());
		File targetDir = getFile("D:\\temp");
		try {
			copyFileToDirectoryAndNoOverlay(srcFile, targetDir);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Collection<File> fileList=listFiles(targetDir, null, false);
		Collection<String> filenames=Collections2.transform(fileList, new Function<File, String>() {
			@Override
			public String apply(File file) {
				return file.getName();
			}
		});
		System.out.println("【"+targetDir.getAbsolutePath()+"】目录下的文件："+filenames);
	}

	public static void mkdirs(String parent) {
		try {
			org.apache.commons.io.FileUtils.forceMkdir(new File(parent));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
